package cn.ekuma.epos.util;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import org.jdesktop.swingx.JXTable;

import cn.ekuma.data.dao.bean.IKeyed;
import cn.ekuma.epos.businesslogic.ProductUtil;
import cn.ekuma.epos.core.util.ProductSwingUtil;
import cn.ekuma.epos.datalogic.I_DataLogicERP;
import cn.ekuma.epos.module.ERP_UI_Swing_Model;
import cn.ekuma.epos.qkorder.link.JProductShardPanel;
import cn.ekuma.epos.report.JReportDialog;
import cn.ekuma.rabbit.spi.I_ModelPart;

import com.openbravo.basic.LocaleResources;
import com.openbravo.bean.Product;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.ComboBoxValEntry;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.pos.base.AppConfig;
import com.openbravo.pos.base.AppLocal;
import com.openbravo.pos.base.AppView;
import com.openbravo.pos.base.BeanFactoryApp;
import com.openbravo.pos.base.BeanFactoryException;
import com.openbravo.pos.base.I_AppView;
import com.openbravo.pos.forms.JPanelView;
import com.openbravo.pos.panels.JProductFinder;
import com.openbravo.pos.panels.event.ProductChangedListener;
import com.openbravo.pos.panels.link.JQuickProductPanel;
import com.openbravo.pos.panels.link.JSeachProductPanel;
import com.openbravo.pos.panels.model.ProductTableModel;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class JProductLabelPrinterPanel extends javax.swing.JPanel implements JPanelView,BeanFactoryApp, ProductChangedListener,I_ModelPart<ERP_UI_Swing_Model>{
	private JXTable table;
	private I_DataLogicERP dlSales;
	private AppView appView;
	private ProductTableModel productModel;
	private String priceGroup;
	private JTextField jGroupPriceName;
	private LocaleResources reportLocale;
	private JComboBox cbPrinteLabel;
	private JTabbedPane tabbedPane;
	private JTextField textField;
	private JProductFinder productFinder;
	
	public JProductLabelPrinterPanel() {
		initComponents();
		productModel=new ProductTableModel();
		table.setModel(productModel);	
	}
	
	private void initComponents() {
		setLayout(new BorderLayout(0, 0));
		
		JPanel panel = new JPanel();
		panel.setPreferredSize(new Dimension(10, 40));
		add(panel, BorderLayout.NORTH);
		panel.setLayout(null);
		
		JLabel label_1 = new JLabel("价目表");
		label_1.setBounds(324, 13, 54, 15);
		panel.add(label_1);
		
		 jGroupPriceName = new JTextField();
		jGroupPriceName.setBounds(388, 10, 79, 21);
		panel.add(jGroupPriceName);
		
		JLabel label_2 = new JLabel("打印模版");
		label_2.setBounds(477, 13, 69, 15);
		panel.add(label_2);
		
		cbPrinteLabel = new JComboBox();
		cbPrinteLabel.setBounds(567, 10, 87, 21);
		panel.add(cbPrinteLabel);
		
		JButton button = new JButton("打印");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				printProductLabel();
			}
		});
		button.setBounds(659, 9, 59, 23);
		panel.add(button);
		
		JButton btDel = new JButton("删除");
		btDel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				removeSelectRow();
			}
		});
		btDel.setBounds(0, 9, 69, 23);
		panel.add(btDel);
		
		JButton btClear = new JButton("清空");
		btClear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				productModel.resert(null);
			}
		});
		btClear.setBounds(64, 9, 69, 23);
		panel.add(btClear);
		
		textField = new JTextField();
		textField.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				m_jBarcode1ActionPerformed(e);
			}
		});
		textField.setBounds(198, 10, 116, 21);
		panel.add(textField);
		textField.setColumns(10);
		
		JSplitPane splitPane = new JSplitPane();
		splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
		add(splitPane);
		
		JScrollPane scrollPane = new JScrollPane();
		splitPane.setLeftComponent(scrollPane);
		
		table = new JXTable();
		scrollPane.setViewportView(table);
		
		 tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		splitPane.setRightComponent(tabbedPane);
		splitPane.setDividerLocation(300);
	}
	
	private void removeSelectRow(){
		int[] selectedRows = table.getSelectedRows();
		if(selectedRows.length==0)
			return;
		List<Product> objs = new ArrayList();
		for (int i = 0; i < selectedRows.length; i++) {
			objs.add(productModel.getObj(table.convertRowIndexToModel(selectedRows[i])));
		}
		productModel.remove(objs);
	}
	
	@Override
	public Object getBean() {
		return this;
	}
	
	protected void m_jBarcode1ActionPerformed(ActionEvent e) {
    	String sCode=textField.getText();
    	if(sCode.isEmpty()){
            return ;
         }
         boolean isSeachModel=false;
         // precondicion: sCode != null
         try {
             Product oProduct=null;
             if(sCode.matches("^[~～][A-Z0-9]+")){
             	isSeachModel=true;
                   java.util.List<Product> prods=dlSales.listProductByMnemonic(sCode.substring(1));
                   if(prods!=null&&prods.size()>0)
                       if(prods.size()==1)
                          oProduct=prods.get(0);
                       else
                          oProduct=getProductFinder().setProductList(prods);
             }else{
                 oProduct = ProductSwingUtil.getProductInfo(this, dlSales, sCode.trim());
             }
             
             if (oProduct == null) {                  
                 Toolkit.getDefaultToolkit().beep(); 
                 if(!isSeachModel)
                 	new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.noproduct")).show(this);
             } else 
            	 addProductToTable(oProduct); 
         } catch (BasicException eData) {  
             new MessageInf(eData).show(this);           
         }
         textField.selectAll();
	}
	
	public JProductFinder getProductFinder() {
        if(productFinder==null)
            productFinder=JProductFinder.getInstance(this, dlSales,JProductFinder.PRODUCT_ALL);
        return productFinder;
    }
	
	
	@Override
	public void init(I_AppView app) throws BeanFactoryException {
		this.appView=(AppView) app;
		priceGroup=appView.getProperties().getProperty(AppConfig.SALE_PRODUCT_GROUPNAME);
		
		JProductShardPanel jProductShardPanel=new JProductShardPanel(dlSales);
		tabbedPane.addTab(AppLocal.getIntString("Menu.SharedProducts"), jProductShardPanel);
        jProductShardPanel.addProductChangedListener(this);
        
		JQuickProductPanel quickProductPanel=new JQuickProductPanel(dlSales);
		tabbedPane.addTab(AppLocal.getIntString("label.quickProduct"), quickProductPanel);
        quickProductPanel.addProductChangedListener(this); 
        
        JSeachProductPanel seachProductPanel=new JSeachProductPanel(dlSales);
        tabbedPane.addTab(AppLocal.getIntString("label.search"), seachProductPanel);
        seachProductPanel.addProductChangedListener(this); 
		
	}
	@Override
	public String getTitle() {
		return null;
	}
	@Override
	public void activate() throws BasicException {
		jGroupPriceName.setText(priceGroup);
		loadReport();
	}
	
	
	private void printProductLabel(){
		if(productModel.getObjs().isEmpty())
			return;
		try {
            JasperReport jr;
            String resourcefile="/cn/ekuma/reports/productLabel/productLabel.jrxml";
            ComboBoxValEntry entry=(ComboBoxValEntry)cbPrinteLabel.getSelectedItem();
            if(entry!=null)
            	resourcefile="/cn/ekuma/reports/productLabel/"+entry.getKey() + ".jrxml";
            // read and compile the report
            JasperDesign jd = JRXmlLoader.load(getClass().getResourceAsStream(resourcefile));
            jr = JasperCompileManager.compileReport(jd);

            // Construyo el mapa de los parametros.
            Map reportparams = new HashMap();
            try {
                reportparams.put("REPORT_RESOURCE_BUNDLE", ResourceBundle.getBundle("cn/ekuma/reports/productLabel"));
            } catch (MissingResourceException e) {
            }
            JasperPrint jp = JasperFillManager.fillReport(jr, reportparams,new JRBeanCollectionDataSource(productModel.getObjs()));

           JReportDialog.showReport(this,jp);

        } catch (Exception e) {
            MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotloadreport"), e);
            msg.show(this);
            e.printStackTrace();
        }
	}
	
	private void loadReport(){
        String baseDirName="./reports/cn/ekuma/reports/productLabel/";
        reportLocale=new LocaleResources();
        reportLocale.addBundleName("cn/ekuma/reports/productLabel/report");

        File dir=new File(baseDirName);
        if(dir.isDirectory()){
            for(File reportFile:dir.listFiles(new FilenameFilter(){
                @Override
                public boolean accept(File dir, String name) {
                    return name.endsWith(".jrxml");
                }
            })){
                String fileName=reportFile.getName().substring(0, reportFile.getName().lastIndexOf('.'));
                cbPrinteLabel.addItem(new ComboBoxValEntry(fileName,reportLocale.getString(fileName)));
            }
        }
    }
	
	
	@Override
	public boolean deactivate() {
		return true;
	}
	@Override
	public JComponent getComponent() {
		
		return this;
	}

	@Override
	public void baseBeanChanged(IKeyed<String> key, Product obj) {
		try {
		if(obj==null)
			obj=dlSales.getProductInfo(key.getKey());
		addProductToTable(obj);
		} catch (BasicException e) {
			e.printStackTrace();
		}
		
	}
	
	
	public void addProductToTable(Product obj){
		if(jGroupPriceName.getText()!=null&&!jGroupPriceName.getText().isEmpty())
			try {
				ProductUtil.setGroupProductPrice(dlSales, obj, jGroupPriceName.getText());
			} catch (BasicException e) {
				e.printStackTrace();
			}
		productModel.add(obj);
	}

	
	@Override
	public String getModelName() {
		return ERP_UI_Swing_Model.MODEL_NAME;
	}

	
	@Override
	public void setModel(ERP_UI_Swing_Model mode) {
		dlSales = mode.getDLERP();
		
	}
}
